package combo

import (
	"context"
	"time"

	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/ent/combo"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/ent/predicate"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/internal/svc"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/internal/utils/dberrorhandler"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/types/pancakebot"

	"github.com/suyuan32/simple-admin-common/utils/pointy"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetComboListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetComboListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetComboListLogic {
	return &GetComboListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetComboListLogic) GetComboList(in *pancakebot.ComboListReq) (*pancakebot.ComboListResp, error) {
	var predicates []predicate.Combo
	if in.CreatedAt != nil {
		predicates = append(predicates, combo.CreatedAtGTE(time.UnixMilli(*in.CreatedAt)))
	}
	if in.UpdatedAt != nil {
		predicates = append(predicates, combo.UpdatedAtGTE(time.UnixMilli(*in.UpdatedAt)))
	}
	if in.Name != nil {
		predicates = append(predicates, combo.NameContains(*in.Name))
	}
	if in.Weight != nil {
		predicates = append(predicates, combo.WeightEQ(*in.Weight))
	}
	if in.Calories != nil {
		predicates = append(predicates, combo.CaloriesEQ(*in.Calories))
	}
	
	if in.Price != nil {
		predicates = append(predicates, combo.PriceEQ(*in.Price))
	}
	if in.TotalSales != nil {
		predicates = append(predicates, combo.TotalSalesEQ(int(*in.TotalSales)))
	}
	result, err := l.svcCtx.DB.Combo.Query().Where(predicates...).Page(l.ctx, in.Page, in.PageSize)

	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, in)
	}

	resp := &pancakebot.ComboListResp{}
	resp.Total = result.PageDetails.Total

	for _, v := range result.List {
		resp.Data = append(resp.Data, &pancakebot.ComboInfo{
			Id:         &v.ID,
			CreatedAt:  pointy.GetPointer(v.CreatedAt.UnixMilli()),
			UpdatedAt:  pointy.GetPointer(v.UpdatedAt.UnixMilli()),
			Name:       &v.Name,
			Weight:     &v.Weight,
			Calories:   &v.Calories,
			Price:      &v.Price,
			ImgAddr:    &v.ImgAddr,
			TotalSales: pointy.GetPointer(int64(v.TotalSales)),
		})
	}

	return resp, nil
}
